import { api } from './apiClient'

export interface MeResponse {
  id: string
  username: string
  email: string
  displayName?: string
  nickname?: string
  avatar?: string
  bio?: string
  phone?: string
  birthday?: string
  isOnline?: boolean
  lastSeen?: string
  createdAt: string
  updatedAt: string
  partnerId?: string | null
  partner?: {
    id: string
    username: string
    displayName?: string
    nickname?: string
    avatar?: string
  } | null
}

export interface User {
  id: string
  username: string
  nickname?: string
  avatar?: string
  isOnline: boolean
  lastSeen?: string
  createdAt: string
  partnerId?: string
}

export interface ChangePasswordData {
  currentPassword: string
  newPassword: string
}

export const userApi = {
  getMe: async () => {
    const res = await api.get<{ data: MeResponse }>('/users/me')
    return res.data.data
  },
  bindPartner: async (username: string) => {
    const res = await api.post<{ success: boolean; message?: string }>('/users/bind', { username })
    return res.data
  },
  unbindPartner: async () => {
    const res = await api.delete<{ success: boolean; message?: string }>('/users/bind')
    return res.data
  },
  updateProfile: async (data: { nickname?: string; avatar?: string }) => {
    const res = await api.put<{ success: boolean; data: any; message?: string }>('/users/me', data)
    return res.data
  },
  uploadAvatar: async (file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    const res = await api.post<{ success: boolean; data: any; message?: string }>('/users/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    return res.data
  },
  changePassword: async (data: ChangePasswordData) => {
    const res = await api.put<{ success: boolean; message?: string }>('/users/change-password', data)
    return res.data
  },
  // 管理员功能
  getAllUsers: async () => {
    const res = await api.get<{ success: boolean; data: User[] }>('/users/admin/all')
    return res.data.data
  },
  updateUser: async (userId: string, data: { username?: string; nickname?: string; avatar?: string }) => {
    const res = await api.put<{ success: boolean; data: User; message?: string }>(`/users/admin/${userId}`, data)
    return res.data
  },
  resetUserPassword: async (userId: string, newPassword: string) => {
    const res = await api.put<{ success: boolean; message?: string }>(`/users/admin/${userId}/reset-password`, { newPassword })
    return res.data
  },
  deleteUser: async (userId: string) => {
    const res = await api.delete<{ success: boolean; message?: string }>(`/users/admin/${userId}`)
    return res.data
  }
}
export default userApi